import React, { useState } from 'react';
import styles from './index.less';
import {
  DatePicker,
  Space,
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
  Popover,
  Spin,
  Tooltip,
} from 'antd';
import { ADetail, absenceDetailObject } from '@/pages/admin/absence/aDetail';
import { CourseEditObject } from '@/pages/admin/course/cEdit';
import { UserEditObject } from '@/pages/admin/teacherInfo/tEdit';
import request from '@/http';
import qs from 'qs';
import { Link } from 'react-router-dom';
import { askForLeave } from '@/pages/login/service';

const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  function onChange(value: any, dateString: any) {
    console.log('Selected Time: ', value);
    console.log('Formatted Selected Time: ', dateString);
  }

  function onOk(value: any) {
    console.log('onOk: ', value);
  }

  const [aDetailObject, setADetailObject] = React.useState<absenceDetailObject>(
    {
      isModalVisible: false,
    },
  );

  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 1,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '200', '500'],
  });

  const [currentEditObject, setCurrentEditObject] =
    React.useState<UserEditObject>({
      isModalVisible: false,
    });
  const [formObject] = Form.useForm();

  const [searchValue, setSearchValue] = React.useState('');
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    const ds = {
      ...userParams,
      current: pageValue ? pageValue : 1,
      size: pageSize ? pageSize : 5,
    };

    console.log(ds);
    const result: any = await request.post(
      '/api/admin/adminLeavesController/getStudentLeaveRecordsPage',
      qs.stringify(ds),
    );
    console.log('请假记录：', result);
    if (result && result.code === 200) {
      const data: any = result.data.records.map((user: any) => ({
        key: `user_${user.leaveId}`,
        id: user.leaveId, //	id
        stuId: user.stuId, //  学生id
        studentName: user.studentName, //  学生姓名
        userNo: user.userNo, //  学生姓名
        leaveId: user.leaveId, //	请假id
        theme: user.theme, //	请假主题
        leaveType:
          user.leaveType == 1 ? '事假' : user.leaveType == 2 ? '其他' : '病假', //	请假原因 1 事假 0 病假 2 其他)
        reason: user.reason, //	请假说明
        startTime: user.startTime, //	开始时间
        submitTime: user.submitTime, //	申请时间
        className: user.className, //班级名
        collegesName: user.collegesName, //	学院名
        gradeName: user.gradeName, //	年级名
        majorName: user.majorName, //	专业名
        teamName: user.teamName, //	小组名
        classTeacher: user.classTeacher, //	班主任（审批人）
        status:
          user.status == 0 ? '审批中' : user.status == 2 ? '通过' : '未通过', //	请假审批状态 0 审批不通过 1 审批中 2 审批通过
      }));

      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.records, //总条数 分页
      };
      setPagination(newPageObject);
      setDataSource(data);
      setLoadingState({ loading: false });
      // console.log(data)
    }
  };

  //搜索框取值   localStorage存储
  const [cCollegeData, setCCollegeData] = useState<any[]>([]);
  const getCollage = async () => {
    const chooseCollege: any = await request.get('/queryAllCollege');
    // if (result.code === 200) {
    const cCollege = chooseCollege.map((user: any) => ({
      key: `user_${user.collegeId}`,
      id: user.collegeId,
      collegeId: user.collegeId,
      collegesName: user.collegesName,
    }));
    localStorage.setItem('collegesName', JSON.stringify(cCollege));
    let college = localStorage.getItem('collegesName');
    if (college) {
      setCCollegeData(JSON.parse(college));
    }
  };

  const [cMajorData, setCMajorData] = useState<any[]>([]);
  const getMajor = async () => {
    const chooseMajor: any = await request.get('/queryAllMajor');
    const cMajor = chooseMajor.map((user: any) => ({
      key: `user_${user.majorId}`,
      id: user.majorId,
      majorId: user.majorId,
      majorName: user.majorName,
    }));
    localStorage.setItem('major', JSON.stringify(cMajor));
    let major = localStorage.getItem('major');
    if (major) {
      setCMajorData(JSON.parse(major));
    }
  };

  const [cGroupData, setCGroupData] = useState<any[]>([]);
  const getGroup = async () => {
    const chooseMajor: any = await request.get('/queryAllGroup');
    const cMajor = chooseMajor.map((user: any) => ({
      key: `user_${user.groupId}`,
      id: user.groupId,
      groupId: user.groupId,
      teamName: user.teamName,
    }));
    localStorage.setItem('major', JSON.stringify(cMajor));
    let major = localStorage.getItem('major');
    if (major) {
      setCGroupData(JSON.parse(major));
    }
  };

  const [cGradeData, setCGradeData] = useState<any[]>([]);
  const getGrade = async () => {
    const chooseGrade: any = await request.get('/queryAllGrade');
    const cGrade = chooseGrade.map((user: any) => ({
      key: `user_${user.gradeId}`,
      id: user.gradeId,
      gradeId: user.gradeId,
      gradeName: user.gradeName,
    }));
    localStorage.setItem('gradeName', JSON.stringify(cGrade));
    let grade = localStorage.getItem('gradeName');
    if (grade) {
      setCGradeData(JSON.parse(grade));
    }
  };

  const [cClassData, setCClassData] = useState<any[]>([]);
  const getClasses = async () => {
    const chooseClass: any = await request.get('/queryAllClass');

    const cClass = chooseClass.map((user: any) => ({
      key: `user_${user.classId}`,
      id: user.classId,
      classId: user.classId,
      className: user.className,
    }));

    localStorage.setItem('classname', JSON.stringify(cClass));
    let Class = localStorage.getItem('classname');
    if (Class) {
      setCClassData(JSON.parse(Class));
    }
  };

  //班主任
  const [cHeadTeacherData, setCHeadTeacherData] = useState<any[]>([]);
  const getHeadTeacher = async () => {
    const chooseHeadTeacher: any = await request.get('/queryAllApprover');
    const cHeadTeacher = chooseHeadTeacher.map((user: any) => ({
      key: `user_${user.teacherId}`,
      id: user.teacherId,
      teacherId: user.teacherId,
      teacherName: user.teacherName,
    }));
    localStorage.setItem('headTeacher', JSON.stringify(cHeadTeacher));
    let headTeacher = localStorage.getItem('headTeacher');
    if (headTeacher) {
      setCHeadTeacherData(JSON.parse(headTeacher));
    }
  };

  //搜索
  const searchOnClick = async () => {
    console.log(formObject.getFieldsValue());
    await loadDataSource(formObject.getFieldsValue(), 1, pagination.pageSize);
  };

  //生命周期函数
  React.useEffect(() => {
    loadDataSource(null, 1, pagination.pageSize).finally();
    // getMajor()
    // getCollage()
    // getGrade()
    // getClasses()
    // getHeadTeacher()
    // getGroup()
  }, []);

  //换页
  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  async function userEditOnClose() {
    await loadDataSource(
      formObject.getFieldsValue(),
      pagination.current,
      pagination.pageSize,
    );
  }

  const [reason, setreason] = useState('请假');
  const content = <div className="reasonContent">{reason}</div>;

  return (
    <div className="pageMain">
      <div className="pageContent">
        <div className="search" style={{ width: '1400px' }}>
          <div className={styles.searchForm}>
            <Form layout="inline">
              <Form.Item label="日期" name="submitTime">
                <DatePicker
                  style={{ width: 220 }}
                  className="itemAttendanceSelect"
                />
              </Form.Item>
              <Form.Item label="院系" name="collegesName" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>

                  {cCollegeData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.collegeId}
                        children={item.collegesName}
                      />
                    );
                  })}
                </Select>
              </Form.Item>

              <Form.Item
                label="专&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业"
                name="majorName"
                initialValue=""
              >
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cMajorData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.majorId}
                        children={item.majorName}
                      />
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                label="年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;级"
                name="gradeName"
                initialValue=""
              >
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cGradeData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.gradeId}
                        children={item.gradeName}
                      />
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item label="班级" name="className" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cClassData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.classId}
                        children={item.className}
                      />
                    );
                  })}
                </Select>
              </Form.Item>

              <Form.Item label="小组" name="teamName" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cGroupData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.groupId}
                        children={item.teamName}
                      />
                    );
                  })}
                </Select>
              </Form.Item>
              <Form.Item label="请假原因" name="leaveType" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  <Option value="0">请假原因1</Option>
                  <Option value="1">请假原因2</Option>
                </Select>
              </Form.Item>
              <Form.Item label="学生姓名" name="studentName">
                <Input
                  className="itemAttendanceInput"
                  placeholder="请输入..."
                />
              </Form.Item>
              <Form.Item label="学号" name="userNo">
                <Input
                  className="itemAttendanceInput"
                  placeholder="请输入..."
                />
              </Form.Item>

              <Form.Item label="主题" name="theme" initialValue="">
                <Input
                  className="itemAttendanceInput"
                  placeholder="请输入..."
                />
              </Form.Item>
              <Form.Item label="审批人员" name="classTeacher" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  {cHeadTeacherData.map((item: any, index: any) => {
                    return (
                      <Option
                        index={index}
                        key={index}
                        value={item.teacherName}
                        children={item.teacherName}
                      />
                    );
                  })}
                </Select>
              </Form.Item>

              <Form.Item label="审批状态" name="status" initialValue="">
                <Select className="itemAttendanceSelect">
                  <Option value="">请选择...</Option>
                  <Option value="0">待处理</Option>
                  <Option value="1">已处理</Option>
                </Select>
              </Form.Item>

              <Form.Item>
                <Button type="primary" onClick={searchOnClick}>
                  查询
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>

        <div className="abTable">
          <Spin tip="Loading..." spinning={loadingState.loading}>
            <Table
              scroll={{ x: '1200' }}
              columns={[
                {
                  title: '申请提交日期',
                  dataIndex: 'submitTime',
                  key: 'submitTime',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '院系',
                  dataIndex: 'collegesName',
                  key: 'collegesName',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '专业',
                  dataIndex: 'majorName',
                  key: 'majorName',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '年级',
                  dataIndex: 'gradeName',
                  key: 'gradeName',
                  width: 50,
                  align: 'center',
                },
                {
                  title: '班级',
                  dataIndex: 'className',
                  key: 'className',
                  width: 50,
                  align: 'center',
                },
                {
                  title: '小组',
                  dataIndex: 'teamName',
                  key: 'teamName',
                  width: 50,
                  align: 'center',
                },

                {
                  title: '学生姓名',
                  dataIndex: 'studentName',
                  key: 'studentName',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '学号',
                  dataIndex: 'userNo',
                  key: 'userNo',
                  width: 75,
                  align: 'center',
                },

                {
                  title: '主题',
                  dataIndex: 'theme',
                  key: 'theme',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '请假原因',
                  dataIndex: 'leaveType',
                  key: 'leaveType',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '原因说明',
                  dataIndex: 'reason',
                  key: 'reason',
                  width: 75,
                  align: 'center',
                  render: (row: any, text: any) => (
                    <>
                      <Tooltip
                        placement="top"
                        color={'blue'}
                        title={
                          <div className="reasonContent">{text.reason}</div>
                        }
                      >
                        <Button type="link">{text.reason}</Button>
                      </Tooltip>
                    </>
                  ),
                },
                {
                  title: '审批人员',
                  dataIndex: 'classTeacher',
                  key: 'classTeacher',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '审批状态',
                  dataIndex: 'status',
                  key: 'status',
                  width: 75,
                  align: 'center',
                },

                {
                  title: '操作',
                  key: 'action',
                  align: 'center',
                  width: 75,
                  render: (row: any, text: any) => (
                    <>
                      <Link to="/admin/attendance/absenceReason">
                        <Button
                          type="link"
                          onClick={() => {
                            askForLeave.saveAskForLeaveId({
                              id: text.id,
                              status: text.status,
                            });
                          }}
                        >
                          详情
                        </Button>
                      </Link>
                    </>
                  ),
                },
              ]}
              dataSource={dataSource}
              pagination={pagination}
              onChange={pageOnChange}
              tableLayout="fixed"
              bordered
            />
          </Spin>
        </div>
        <ADetail editObject={aDetailObject} />
      </div>
    </div>
  );
};
